package com.cmdandroid.icebutton;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

//This is the main screen of the application
public class ICEButtonMainActivity extends ICEButtonActivity implements LocationListener {
	
	static final int DIALOG_LOCATION_QUESTION = 0;
	static final int DIALOG_ENTER_LOCATION=1;
	static final int DIALOG_MESSAGE_QUESTION=2;
	static final int PICK_CONTACT_REQUEST = 0;
	static final int EDIT_MESSAGE_REQUEST = 1;
	static final int MANAGE_CONTACT_REQUEST = 2;
	
	public ArrayList<String> names = new ArrayList<String>(); //Will hold our names
	public ArrayList<String> numbers = new ArrayList<String>(); //Will hold our numbers

	public GPSCoords currentCoords; //Holds current coordinates
	public String enteredAddr; //Holds user defined address
	public String currentAddr; //Holds current address
	public String tempName;
	public String tempNumber;
	public String enteredMessage;
	
	public String noGPSMessage = "I cannot get a GPS signal";
	
	public long gpsWaitTime = 300000; //Default is 5 mins
	
	public boolean canceled = false;
	public boolean showCopyOfSMS = true;
	
	
	public String defaultMessage = "I am at "; //needs to be user changable in settings
	
	public boolean gotLoc = false; //Determines if location has been determined
	public boolean setMessage = false; //Determines if user saved a message
	LocationManager locMgr;
	
	public boolean timeOut = false;
	

	
	SmsManager smsMgr = SmsManager.getDefault();
	
	public SharedPreferences appPrefs;
	
	

	
	public static int numContacts;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Show EULA
        Eula.show(this);
        
        appPrefs = getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
        initLocationTools(); //Initialize location tools
        
        initButtons();
        
        initData();
        

        
        
   //     Toast.makeText(getApplicationContext(), tempName, Toast.LENGTH_LONG);
	}
	
	//Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu, menu);
		menu.findItem(R.id.app_manage);
		menu.findItem(R.id.app_message);
		menu.findItem(R.id.app_about);
		menu.findItem(R.id.app_preferences);
		menu.findItem(R.id.app_help);
		return true;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    super.onOptionsItemSelected(item);
	    switch (item.getItemId()) {
	    case R.id.app_about:
	    	Intent optionsIntent = new Intent(getApplicationContext(),
	    			ICEButtonAboutActivity.class);
	    	startActivity(optionsIntent);
	    	return true;
	    case R.id.app_help:
	    	Intent helpIntent = new Intent(getApplicationContext(),
	    			ICEButtonHelpActivity.class);
	    	startActivity(helpIntent);
	    	return true;
	    case R.id.app_message:
	    	Intent intent1 = new Intent(getApplicationContext(),
	    			ICEButtonEditMessageActivity.class);
	    	startActivityForResult(intent1, EDIT_MESSAGE_REQUEST);
	    	return true;
	    case R.id.app_manage:
	    	Intent intent2 = new Intent(getApplicationContext(),
	    			ICEButtonManageContactsActivity.class);
	    	Bundle b = new Bundle();
	    	ArrayList<String> infoToManage= new ArrayList<String>();
	    	
	    	//Build info
	    	for (int i=0; i<names.size(); i++){
	    		infoToManage.add(names.get(i));
	    		infoToManage.add(numbers.get(i));
	    	}
	    	
	    	b.putStringArrayList(CONTACTDATAKEY_INFO, infoToManage);
	    	intent2.putExtras(b);
	    	startActivityForResult(intent2, MANAGE_CONTACT_REQUEST);
	    	
	    	return true;
	    case R.id.app_preferences:
	    	Intent prefsIntent = new Intent(getApplicationContext(),
	    			ICEButtonPrefsActivity.class);
	    	startActivity(prefsIntent);
	    default:
	    	return true;
	    }
	}
	
	@Override
    public void onPause() {
    	locMgr.removeUpdates(ICEButtonMainActivity.this); //Stop GPS if paused
    	super.onPause();
    }
	
	 @Override
	    public void onResume() {
		 	//Resume GPS is resumed
			locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, ICEButtonMainActivity.this);
			super.onResume();
	    }

	@Override
	public void onLocationChanged(Location location) { //when location has changed
		if (location != null)
		{
			 StringBuilder sb = new StringBuilder();
			 float lat = (float) location.getLatitude();
			 float lon = (float) location.getLongitude();
			 currentCoords = new GPSCoords(lat, lon); //Store coordinates
			 currentAddr = getAddress(currentCoords); //Attempt to get address
			 gotLoc = true;
			 //FOR DEBUG
			
			 sb.append("Got Location!: ");sb.append(lat); sb.append(" : "); sb.append(lon); sb.append(" : "); sb.append(currentAddr);
				Toast.makeText(ICEButtonMainActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
				
		    
			//showDialog(DIALOG_ENTER_LOCATION);
		}
		
	}
	
	@Override
	//when activity is returned to and a result has been sent
	public void onActivityResult(int reqCode, int resultCode, Intent data){
		//Check req code
		if (reqCode == PICK_CONTACT_REQUEST) {
			//Did the activity end OK?
			if (resultCode == Activity.RESULT_OK) {
				//Extract extras
				Bundle extras = data.getExtras();
	
				tempName = extras.getString(CONTACTDATAKEY_NAME);
				
				//Get all phone numbers from extras
				Integer i = 0;
				List<String> allNumbers = new ArrayList<String>();
				do{
					allNumbers.add(extras.getString(CONTACTDATAKEY_NUMBER+i));
					i++;
				}
				while (extras.containsKey(CONTACTDATAKEY_NUMBER + i));
				
				//Create AlertDialog to pick from list of phone numbers
				final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
                AlertDialog.Builder builder = new AlertDialog.Builder(ICEButtonMainActivity.this);
                builder.setTitle("Choose a number");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String selectedNumber = items[item].toString();
                        //We can include this if we want to filter out dashes
                        //selectedNumber = selectedNumber.replace("-", "");
                        
                        //Filter out brackets that sometimes appear
                        selectedNumber = selectedNumber.trim();
                        selectedNumber = selectedNumber.replace("[", "");
                        selectedNumber = selectedNumber.replace("]", "");

        				updateData(selectedNumber);
                    }
                });
                AlertDialog alert = builder.create();
                //If more than one number, show AlertDialog to pick number
                if(allNumbers.size() > 1) {
                    alert.show();
                //Else, just use the one number
                } else {
                    String selectedNumber = allNumbers.toString();
                    selectedNumber = selectedNumber.trim();
                    selectedNumber = selectedNumber.replace("[", "");
                    selectedNumber = selectedNumber.replace("]", "");
                    //We can include this if we want to filter out dashes
                    //selectedNumber = selectedNumber.replace("-", "");
                    //phoneInput.setText(selectedNumber);
                    
                    updateData(selectedNumber);

                }
				
			}
		}
			
		else if (reqCode == EDIT_MESSAGE_REQUEST) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle extras = data.getExtras();
				//Save in temporary
				//May not need this
				enteredMessage = extras.getString(MESSAGEDATAKEY);
				if (enteredMessage.equals("")) {
					setMessage = false;
				}
				else {
					setMessage = true;
				}
				writeString(PREFS_MESSAGE, enteredMessage);
			}
		}
		
		else if (reqCode == MANAGE_CONTACT_REQUEST) {
			if (resultCode == Activity.RESULT_OK) {
				
				ArrayList<String> info = new ArrayList<String>();
				
				Bundle extras = data.getExtras();
				
				
				info =  extras.getStringArrayList(CONTACTDATAKEY_INFO);
				
				numbers.clear();
				names.clear();
				
				for (int i = 0; i<info.size(); i=i+2) {
					names.add(info.get(i));
					numbers.add(info.get(i+1));
				}
				
				if (names.size() == numbers.size()) 
				{
					numContacts = names.size();
					writeData();
				}
				else
				//Something went wrong with numbers and names
				{
					Toast.makeText(getApplicationContext(), "An error has occured. " +
							"Your contacts have been reset", Toast.LENGTH_LONG).show();
					names.clear();
					numbers.clear();
					
					for (int i=0; i<numContacts; i++) {
						clearKey((PREFS_NAMES + i));
						clearKey((PREFS_NUMBERS + i));
					}
					
					clearKey(PREFS_NUM_CONTACTS);
					numContacts = 0;
				}
				
				
			}
		}
	}
	
	public void updateData(String selectedNumber) {
		//Add to end of ArrayLists
		//Check to make sure the user isn't adding
		//duplicate number
		if (numbers.contains(selectedNumber)) {
			Toast.makeText(getApplicationContext(), "That number is already stored!", Toast.LENGTH_LONG).show();
		}
		//If not a duplicated number, write data
		else {
        numContacts++;
		writeInt(PREFS_NUM_CONTACTS, numContacts);
		names.add(tempName);
		//numContacts - 1 because of PREFS_NAMES format
		writeString((PREFS_NAMES + (numContacts-1)), tempName);
		numbers.add(selectedNumber);
		//numContacts - 1 because of PREFS_NAMES format
		writeString((PREFS_NUMBERS + (numContacts-1)), selectedNumber);
        //phoneInput.setText(selectedNumber);
		Toast.makeText(getApplicationContext(), tempName + " : " + selectedNumber,
				Toast.LENGTH_LONG).show();
		}
		
	}
	

	
	public void writeData() {
		writeInt(PREFS_NUM_CONTACTS, numContacts);
		for (int i=0; i<names.size(); i++)
		{
			writeString((PREFS_NAMES + i), names.get(i));
			writeString((PREFS_NUMBERS + i), numbers.get(i));
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	protected Dialog onCreateDialog(int id){
		Dialog dialog = null;
		switch(id) {
		case DIALOG_LOCATION_QUESTION:
			dialog = createLocationQuestionsDialog();
			break;
			
		case DIALOG_ENTER_LOCATION:
			dialog = createGetLocationDialog();
			break;
			
		case DIALOG_MESSAGE_QUESTION:
			dialog = createQuestionSetMessage();
		}
		
		return dialog;
	}
	
	 private void initLocationTools() { //initialize Location Tools
	     
			locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, ICEButtonMainActivity.this);
		}
	 
	 private void initButtons() {
		 
		 Button ICEButton = (Button) findViewById(R.id.button_ICE_Button);
		 Button contactButton = (Button) findViewById(R.id.button_addContact);
		 
		 ICEButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (numbers.isEmpty()){  //Check if the user has added any contacts
					Toast.makeText(getApplicationContext(), "Please add at least one contact", Toast.LENGTH_LONG).show();
				}
				
				else {
					//Check if user has set a message
					if (setMessage == false) {
						showDialog(DIALOG_MESSAGE_QUESTION);
					}
					else
					{
						showDialog(DIALOG_LOCATION_QUESTION);
					}
				}
			
			}
		});
		 
		 contactButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent getContact = new Intent(ICEButtonMainActivity.this,
		        		ICEButtonAddContactsActivity.class);
		       startActivityForResult(getContact, PICK_CONTACT_REQUEST);
			}
		});
	 }
	 
	 private String getAddress(GPSCoords currentCoords) //Attempt to get address from currentCoords
	 {
		 String Addr= null;
		   Geocoder gcd = new Geocoder(ICEButtonMainActivity.this, Locale.getDefault());
		   try {
			List<Address> addresses = gcd.getFromLocation((double)currentCoords.mLat,
					   (double)currentCoords.mLon, 1);
			   if (addresses.size() >0) {
				   Addr=(addresses.get(0).getAddressLine(0));
			   }
		   } catch (IOException e) {
			e.printStackTrace();
		   }
		 
		 return Addr;
	 }
	 
	 private class GPSCoords { //store lat and lon
	        float mLat, mLon;
	        GPSCoords(float lat, float lon) {
	            mLat = lat;
	            mLon = lon;
	        }
	        @SuppressWarnings("unused")
			private void insert(float coordinate, boolean lat) {
	        	if (lat) {
	        		mLat = coordinate;
	        	}
	        	else {
	        		mLon = coordinate;
	        	}
	        }
	    }
	 
	public Dialog createQuestionSetMessage() {
		 
		 //This Dialog is used for determining if the user wants to enter a message or use default
		 AlertDialog.Builder messageQuestionBox = new AlertDialog.Builder(this);
		 
		 messageQuestionBox.setTitle(R.string.dialog_message_question_Title);
		 
		 messageQuestionBox.setMessage(R.string.dialog_message_question_Body);
		 
		 messageQuestionBox.setNegativeButton("Use Default", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showDialog(DIALOG_LOCATION_QUESTION);
				dialog.dismiss();
			}
		});
		 
		 //TODO: Maybe add cencelable
		 
		 messageQuestionBox.setPositiveButton("Create Message", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
		    	Intent intent = new Intent(getApplicationContext(),
		    			ICEButtonEditMessageActivity.class);
		    	startActivityForResult(intent, EDIT_MESSAGE_REQUEST);
		    	
		    	dialog.dismiss();
			}
		});
		 
		 return messageQuestionBox.create();
	 }
	 
	 
	 private Dialog createLocationQuestionsDialog()
	 {
		 //This Dialog is used for determining if the user wants to enter their location manually
		 AlertDialog.Builder locationBox = new AlertDialog.Builder(this);
		 
		 locationBox.setMessage("Would you like to enter your location manually?");
		 
		 //Button used to cancel the Dialog
		 locationBox.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
		
			public void onClick(DialogInterface dialog, int which) {
				//Toast.makeText(getApplicationContext(), "Neutral Clicked", Toast.LENGTH_SHORT).show();
				
			}
		});
		 
		 //The user wants to enter their location manually
		 locationBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				//Toast.makeText(getApplicationContext(), "Positive Clicked", Toast.LENGTH_SHORT).show();
				showDialog(DIALOG_ENTER_LOCATION); //Open Enter Location dialog

				dialog.dismiss(); //Dismiss this dialog for performance
			}
		});
		 
		 //The user wants to use GPS
		 locationBox.setNegativeButton("Use GPS", new DialogInterface.OnClickListener() {
		
			public void onClick(DialogInterface dialog, int which) {
				//Toast.makeText(getApplicationContext(), "Negative Clicked", Toast.LENGTH_SHORT).show();
				//TODO: Implement background process to wait for GPS fix
				

					if (!(currentAddr != null && !currentAddr.equals(""))){ //if currentAddr is null
						if(gotLoc) {//if currentCoords is NOT null
							StringBuilder sb = new StringBuilder();
							currentAddr = currentAddr + ". My coordinates are: " + sb.append(currentCoords.mLat).append(" ")
							.append(currentCoords.mLon).toString();
							
							//If user has not set a message
								if (setMessage == false ){ 
									SMS(numbers, defaultMessage, currentAddr);
									}
								
								else{ //if setMessage is TRUE
									SMS(numbers, enteredMessage, currentAddr);
								}
						}
						else{ //if currentCoords IS null
							
							//Add thread and indefinite progressDialog until GPS has fix
							

							//Hanler for timer
							final Handler handler = new Handler();
							
							//Timer runnable
							final Runnable timer = new Runnable() {
								public void run() {
									timeOut = true;
								}
							};
							

							final Dialog gpsDialog = ProgressDialog.show(ICEButtonMainActivity.this, "Please wait...",
									"Retrieving GPS data ...", true, true, new DialogInterface.OnCancelListener() {
										
										@Override
										public void onCancel(DialogInterface dialog) {
											
											handler.removeCallbacks(timer);
											dialog.dismiss();
											
											canceled = true;
										}
									});
							
							//Runnable for thread
							Runnable showWaitDialog = new Runnable() {

								@Override
								public void run() {
										while (gotLoc == false && timeOut == false && canceled == false) {
											//wait for gotLoc or timeOut or canceled to be true 
										};
										//If use did not cancel task
										if (canceled == false) {
											//If run was called by a timeOut, send text with NO GPS message
											if (timeOut == true) {
												if (setMessage == false) {
													SMS(numbers, defaultMessage, noGPSMessage ); //TODO: Make noGPSMessage edittable
												}
												else {
													SMS(numbers, enteredMessage, noGPSMessage);
												}
											}
											//If run was called by GPS fix, send text with current address
											else {
												if (setMessage == false) {
													SMS(numbers,defaultMessage, currentAddr);
												}
												else {
													SMS(numbers, enteredMessage, currentAddr);
												}
												
												handler.removeCallbacks(timer);
											}
											//Dismiss the dialog
											gpsDialog.dismiss();
									}
								}
								
							};
							
							//Read shared preferences to see if gpsWaitTime has been changed
							if (appPrefs.contains(PREFS_GPS_WAIT_TIME)) {
								 gpsWaitTime = Long.decode(readString(PREFS_GPS_WAIT_TIME));
							 }
							 else {
								 gpsWaitTime = 300000;
							 }

							handler.postDelayed(timer, gpsWaitTime);
							
							Thread t = new Thread(showWaitDialog);
							t.start();
							
							//Don't need this anymore because of added thread
							//Toast.makeText(getApplicationContext(),
							//		"Location not found yet. Please wait or enter location manually",
							//		Toast.LENGTH_LONG).show();
						}
					}
					else{ //If currentAddr is NOT null
						if (setMessage == false) {
							SMS(numbers, defaultMessage, currentAddr);
						}
						else{
							SMS(numbers, enteredMessage, currentAddr);
						}
					}
				}
		});
		 
		 return locationBox.create();
	 }
	 
	 private Dialog createGetLocationDialog()
	 {
		 LayoutInflater inflater1 = (LayoutInflater) getSystemService(ICEButtonMainActivity.LAYOUT_INFLATER_SERVICE);
		 final View layout1 = inflater1.inflate(R.layout.dialog_enter_location, (ViewGroup) findViewById(R.id.linearLayout_root));
		 final EditText locationText = (EditText) layout1.findViewById(R.id.editText_dialog_location);
		 final Button posButton = (Button) layout1.findViewById(R.id.button_dialog_enter_location_positive);
		 final Button negButton = (Button) layout1.findViewById(R.id.button_dialog_enter_location_negative);
		 posButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//Toast.makeText(getApplicationContext(), "POS Clicked", Toast.LENGTH_SHORT).show();
				
				//check to make sure user entered a location
				//if not, send a toast and keep dialog open
				if (locationText.getText().toString().equalsIgnoreCase(
						getApplicationContext().getString(R.string.edit_text_enter_location_Text)))
				{
					Toast.makeText(getApplicationContext(), "Please enter your location", Toast.LENGTH_SHORT).show();
				}
				
				//else, save locatoin and dismiss dialog
				else{
				enteredAddr = locationText.getText().toString(); //save user location
				if (setMessage == false){ 
					SMS(numbers, defaultMessage, enteredAddr);
				}
				else{
					SMS(numbers, enteredMessage, enteredAddr);
				}
				dismissDialog(DIALOG_ENTER_LOCATION);
				
			}
				
			 
		 }
		});
		 
		 negButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
			//	Toast.makeText(getApplicationContext(), "NEG Clicked", Toast.LENGTH_SHORT).show();
				dismissDialog(DIALOG_ENTER_LOCATION);
			}
		});
		AlertDialog.Builder locationAnswer = new AlertDialog.Builder(this);
		locationAnswer.setView(layout1);
		locationAnswer.setTitle("Enter your location");
		locationAnswer.setCancelable(true);
		
		AlertDialog locationDialog = locationAnswer.create();
		return locationDialog; 
	 }
	 
	 public void writeString (String key, String data)
	 {
		 Editor editor = appPrefs.edit();
		 editor.putString(key, data);
		 editor.commit();
	 }
	 
	 public String readString (String key) {
		 return appPrefs.getString(key, "");
	 }
	 
	 public int readInt (String key) {
		 return appPrefs.getInt(key, 0);
	 }
	 
	 public void writeInt (String key, int data) {
		 Editor editor = appPrefs.edit();
		 editor.putInt(key, data);
		 editor.commit();
	 }
	 
	 public boolean readBool (String key) {
		 return appPrefs.getBoolean(key, true);
	 }
	 
	 public void writeBool (String key, boolean data) {
		 Editor editor = appPrefs.edit();
		 editor.putBoolean(key, data);
		 editor.commit();
	 }
	 
	public void clearAllData() {
			Editor editor = appPrefs.edit();
			editor.clear();
			editor.commit();
	}
	
	public void clearKey (String key) {
		Editor editor = appPrefs.edit();
		editor.remove(key);
		editor.commit();
	}
	 
	 public void initData() {

		 if (appPrefs.contains(PREFS_NUM_CONTACTS)) {
			 numContacts = readInt(PREFS_NUM_CONTACTS);
		 }
		 else{
			 numContacts = 0;
		 }
		 
		 if (appPrefs.contains(PREFS_MESSAGE)) {
			 enteredMessage = readString(PREFS_MESSAGE);
			 setMessage = true;
		 }
		 else{
			 enteredMessage = "";
		 	 setMessage = false;
		 }
		 

		 
		 
		 //recall saved names and numbers
		 //format for PREFS_NUMBERS is PREFS_NUMBERS + location
		 //format for PREFS_NAMES is the same
		 //location starts at 0 and ends at numContacts-1
		 for (int i = 0; i<numContacts; i++) {
			 numbers.add(readString(PREFS_NUMBERS + i));
			 names.add(readString(PREFS_NAMES + i));
		 }
		 
		 
		 
	 }
	 
	 
//				SMS FUNCTION
	 private void SMS( ArrayList<String> Contacts, String message, String addr)
	 {
         try { 
	    	 String MyMessage= message + " " +  addr;
		     for (int i=0; i<(Contacts.size()); i++){
		    	 
		    	 String sendTo=Contacts.get(i).toString();
		     	 smsMgr.sendTextMessage(sendTo, null, MyMessage, null, null);//sends the text message
		     }
	
	        	  //Check if user wants to show copy of sms
	     		 if (appPrefs.contains(PREFS_SHOW_COPY)) {
	    			 showCopyOfSMS = readBool(PREFS_SHOW_COPY);
	    		 }
	    		 else {
	    			 showCopyOfSMS = true;
	    		 }
	        	  
	        	  Toast toast;
	        	  
	        	  if (showCopyOfSMS) {
	        	   toast = Toast.makeText(ICEButtonMainActivity.this, "SMS SENT! " + MyMessage, Toast.LENGTH_LONG);
	        	  }
	        	  else {
	        		  toast = Toast.makeText(ICEButtonMainActivity.this, "SMS Sent!", Toast.LENGTH_SHORT);
	        	  }
					toast.show();
           } catch (Exception e) { 
        	   Toast toast = Toast.makeText(ICEButtonMainActivity.this, "SMS FAILED!", Toast.LENGTH_LONG);
				toast.show();
           	 }	 
	     	 
	     	 
	     
	     }
}
